package cn.lkx.servicevod.controller;

import cn.lkx.commonutils.R;
import cn.lkx.servicebase.exceptionhandle.MyException;
import cn.lkx.servicevod.service.VodService;
import cn.lkx.servicevod.utils.ConstantVodUtils;
import cn.lkx.servicevod.utils.InitVodClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Api(description = "视频上传阿里云")
@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    VodService vodService;

    //上传视频到阿里云
    @PostMapping("uploadVideo")
    public R uploadVideo(MultipartFile file){
        //获得上传的视频文件file
        //调用服务层方法上传,返回上传的视频id
        String videoId = vodService.uploadVideo(file);
        return R.ok().data("videoId",videoId);
    }

    //根据小节 id删除阿里云上的小节视频
    @DeleteMapping("deleteVideo/{videoId}")
    public R deleteVideo(@PathVariable String videoId){
        vodService.removeVideo(videoId);
        return R.ok();
    }
    //批量删除小节视频（删除课程时调用）
    @DeleteMapping("deleteBatchVideo")
    public R removeVideoList(@RequestParam("videoIdList") List<String> videoIdList){
        vodService.removeVideoList(videoIdList);
        return R.ok();
    }

    //根据视频id获取视频播放凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id){
        try {
            //创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID,ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建获取视频凭证的 request 和response
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //设置请求参数
            request.setVideoId(id);
            //获取请求响应
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            //输出请求结果//播放凭证
            String playAuth = response.getPlayAuth();
            System.out.println("播放凭证：=============="+playAuth);
            return R.ok().data("playAuth",playAuth);
        }catch (Exception e){
            throw new MyException(20001,"获取失败");
        }
    }
}
